package com.changdu.seatunnel.admin.config;

import org.springframework.core.MethodParameter;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.changdu.seatunnel.admin.config.enums.HttpResponseStatus;
import com.changdu.seatunnel.admin.config.model.ExceptionResult;

import jakarta.servlet.http.HttpServletResponse;

@SuppressWarnings("rawtypes")
@RestControllerAdvice
public class ExceptionResultAdvice implements ResponseBodyAdvice, Ordered {

	@Override
	public boolean supports(MethodParameter returnType, Class converterType) {
		return returnType.getParameterType() == ExceptionResult.class;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, 
			ServerHttpRequest request, ServerHttpResponse response) {
		ExceptionResult errorInfo = (ExceptionResult) body;
		HttpServletResponse httpResponse = ((ServletServerHttpResponse) response).getServletResponse();
		httpResponse.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR.value());
		return errorInfo;
	}

	@Override
	public int getOrder() {
		return Integer.MIN_VALUE;
	}

}